﻿using System.IO;
using System.Linq;

namespace Red.Core.Network.PacketNetwork
{
    internal static class PacketCreator
    {
        public static MemoryStream CreatePacket(MemoryStream dataToSend)
        {
            MemoryStream packet = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(packet);
            byte[] content = dataToSend.ToArray();
            uint contentCrc = CalculateCrc32(content);

            writer.Write(Constants.PacketMagic);
            writer.Write(content.Count());
            writer.Write(contentCrc);
            byte[] header = packet.ToArray();

            uint headerCrc = CalculateCrc32(header);
            writer.Write(headerCrc);
            writer.Write(content);

            return packet;
        }

        // Algorithm: FNV-1a
        public static uint CalculateCrc32(byte[] buffer)
        {
            uint hash = Constants.FNVOffsetBasic32;

            for (int i = 0; i < buffer.Count(); ++i)
            {
                hash ^= buffer[i];
                hash *= Constants.FNVPrime32;
            }

            return hash;
        }
    }
}
